<template>
  <main-content
    :title="mode === 'edit' ? '编辑优惠券批次' : '新增优惠券批次'"
    back
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      :label-width="120"
    >
      <el-form-item
        label="批次名称"
        prop="couponBatchName"
        class="common-form-item"
      >
        <el-input
          v-model="form.couponBatchName"
          :max-length="20"
          show-word-limit
          placeholder="请输入批次名称"
          @blur="form.couponBatchName = form?.couponBatchName.trim()"
        />
      </el-form-item>

      <el-form-item
        label="选择优惠券"
        prop="couponDefineId"
      >
        <sc-selector
          v-model="form.couponDefineId"
          type="couponDefine"
          :disabled="disabled"
          :params="{}"
          :show-filter-tags="false"
          :show-expand-pop="false"
          @click-tree-item="handleCouponChange"
        />
      </el-form-item>

      <el-form-item
        label="优惠券数量"
        prop="couponTotalNum"
        class="common-form-item"
      >
        <el-input
          v-model="form.couponTotalNum"
          :max-length="20"
          show-word-limit
          placeholder="请输入优惠券数量(最大9999)"
          :disabled="disabled"
          @blur="form.couponTotalNum = form?.couponTotalNum?.trim()"
        />
      </el-form-item>

      <el-form-item
        label="使用开始时间"
        prop="takeEffectType"
      >
        <el-radio-group
          v-model="form.takeEffectType"
          class="column-radio-group"
        >
          <el-radio :label="0">
            领取后立即使用
          </el-radio>
          <el-radio :label="1">
            领取后第二天可使用
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="使用结束时间"
        prop="useType"
      >
        <el-radio-group
          v-model="form.useType"
          class="column-radio-group"
          @change="handleUseTypeChange"
        >
          <el-radio :label="0">
            <span class="radio-inner-item">
              固定时间
            </span>
            
            <el-date-picker
              v-model="useFixEndTimeModel"
              type="datetime"
              placeholder="请选择固定时间范围"
              class="radio-inner-item"
            />

            <span class="radio-inner-item">
              时间内均可使用
            </span>
          </el-radio>

          <el-radio
            :label="1"
          >
            <div class="endtime-radio-item">
              <div>
                <span class="radio-inner-item">相对开始时间</span>
                <el-input
                  v-model="form.useDayNum"
                  class="radio-inner-item input-width__120"
                />
                <span class="radio-inner-item">天内可使用</span>
              </div>
              <div>
                <el-icon><InfoFilled /></el-icon>
                1 表示当天失效
              </div>
            </div>
          </el-radio>

          <el-radio :label="2">
            <div class="endtime-radio-item">
              <div>
                <span class="radio-inner-item">相对开始时间</span>
                <el-input
                  v-model="form.useMonthNum"
                  class="radio-inner-item input-width__120"
                />
                <span class="radio-inner-item">月内可使用</span>
              </div>
              <div>
                <el-icon><InfoFilled /></el-icon>
                1 表示当月月底失效,2表示次月月底失效,依此类推
              </div>
            </div>
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template
      #fixed-bottom
    >
      <div class="fixed-bottom">
        <el-button
          type="primary"
          @click="submit"
        >
          提交
        </el-button>
      </div>
    </template>
  </main-content>
</template>

<script setup lang="ts">
import type { Ref } from "vue";
import type { FormRules } from "element-plus";
import type { InternalRuleItem } from 'async-validator';
import type { IEditCouponBatchData } from "@/api/modules/marketingTool";
import moment from "moment";
import { ElMessage } from "element-plus"
import { saveOrUpdateCouponBatch, getOneCouponBatch } from "@/api/marketingTool"
import { positiveInteger } from "@/utils/commonRegexp";


const router = useRouter();
const route = useRoute();

const mode = computed(() => route.path.includes('edit') ? 'edit' : 'create')
const disabled = computed(() => form.value.verifyStatus === 1)

const formRef = ref();
const formRules: Ref<FormRules> = ref({
  couponBatchName: [ {
    message: "请输入批次名称",
    trigger: "blur",
    required: true,
  } ],
  couponDefineId: [ {
    message: "请选择优惠券",
    required: true,
  } ],
  couponTotalNum: [ {
    message: "请输入优惠券数量",
    required: true,
    trigger: "blur",
  }, {
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (!positiveInteger.test('' + form.value.couponTotalNum)) {
        callback("请输入正整数")
        return
      }

      if (form.value.couponTotalNum && form.value.couponTotalNum >= 10000) {
        callback("优惠券最大可设置数量为9999")
        return
      }

      callback()
    }
  } ],
  takeEffectType: [ {
    required: true,
    message: "请选择使用开始时间",
    trigger: "change",
  } ],
  useType: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      // 固定时间
      if (form.value.useType === 0) {
        if (!form.value.useFixEndTime) {
          callback("请输入固定时间范围")
          return
        }
      }

      if (form.value.useType === 1) {
        if (!form.value.useDayNum) {
          callback("请输入相对开始时间（天）")
          return
        }

        if (!positiveInteger.test("" + form.value.useDayNum)) {
          callback("相对开始时间（天）需为数字且大于0")
          return
        } 
      }

      if (form.value.useType === 2) {
        if (!form.value.useMonthNum) {
          callback("请输入相对开始时间（月）")
          return
        }

        if (!positiveInteger.test("" + form.value.useMonthNum)) {
          callback("相对开始时间（月）需为数字且大于0")
          return
        } 
      }

      callback()
    }
  } ]
})

const form:Ref<IEditCouponBatchData> = ref({
  id: undefined,
  couponBatchName: "",
  couponDefineId: undefined,
  couponTotalNum: undefined,
  // 使用开始时间
  takeEffectType: 0,
  // 使用结束时间
  useType: 0,
  useFixEndTime: undefined,
  useDayNum: undefined,
  useMonthNum: undefined,
})

const isEmpty = (val: string | number | undefined | null) => val === null || val === undefined || val === '' 

const handleCouponChange = (item: any) => {
  // console.log("tree item", item.data.info)
  const couponDetail = item.data.info
  form.value.takeEffectType = couponDetail.takeEffectType
  form.value.useType = couponDetail.useType
  form.value.useFixEndTime = couponDetail.useFixEndTime
  form.value.useDayNum = couponDetail.useDayNum
  form.value.useMonthNum = couponDetail.useMonthNum
}

// 使用结束时间
const handleUseTypeChange = () => {
  form.value.useFixEndTime = undefined;
  form.value.useDayNum = undefined;
  form.value.useMonthNum = undefined;
  nextTick(() => {
    formRef.value.clearValidate("useType")
  })
}

const useFixEndTimeModel = computed({
  get() {
    return form.value.useFixEndTime
  },
  set(newValue) {
    form.value.useFixEndTime = moment(newValue).valueOf()
  }
})

const submit = () => {
  console.log("form => ", form.value)
  formRef.value?.validate(async (valid: boolean) => {
    console.log("valid", valid)
    if (valid) {
      const rs = await saveOrUpdateCouponBatch(form.value)
      if (rs.code === 200) {
        ElMessage.success("已提交")
        router.back();
      }
    } else {
      ElMessage.error("校验未通过，请检查表单")
    }
  })
}

const _getOneCouponBatch = async () => {
  const rs = await getOneCouponBatch({
    id: <string>route.query.id
  })

  if (rs.code === 200 && rs.payload) {
    form.value = rs.payload
  }
}

// 回显表单
const echoForm = async () => {
  console.log("回显表单！！！")
  await _getOneCouponBatch()

  // 使用结束时间
  if (form.value.useType === 0) {
    useFixEndTimeModel.value = form.value.useFixEndTime
  }
}


onMounted(() => {
  if (mode.value === 'edit') {
    echoForm()
  }
})
</script>

<style scoped lang="scss">
:deep(.common-form-item) {
  .el-form-item__content {
    flex: unset;
  }

  .el-input {
    width: 300px;
  }

  .el-input.form-input__120 {
    width: 120px;
  }

  .gapped-form-item {
    margin-right: 10px;
  }
}

:deep(.column-radio-group) {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .el-radio {
    margin-bottom: 10px;
    height: unset;
  }

  .el-radio__label {
    display: inline-flex;
  }

  .radio-inner-item {
    margin-right: 10px;
  }

  .select-width__120 {
    width: 120px;
  }

  .input-width__120 {
    width: 120px;
  }
}
.fixed-bottom {
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>